package com.meirengu.sms.service.impl;

import com.meirengu.sms.model.SmsRecord;
import com.meirengu.sms.service.SmsService;
import com.meirengu.sms.utils.ConfigUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 短信服务实现类
 *
 * @author Marvin
 * @create 2017-01-15 上午10:34
 */
@Service
public class SmsServiceImpl implements SmsService {

    private static final Logger logger = LoggerFactory.getLogger(SmsServiceImpl.class);

    public String SMS(String postData, String postUrl) {
        try {
            //发送POST请求
            URL url = new URL(postUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Length", "" + postData.length());
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(postData);
            out.flush();
            out.close();
            //获取响应状态
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                System.out.println("connect failed!");
                return "";
            }
            //获取响应内容体
            String line, result = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            while ((line = in.readLine()) != null) {
                result += line + "\n";
            }
            in.close();
            return result;
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
        return "";
    }

    @Override
    public SmsRecord singleSend(String mobile, String text, String ip, String bid) throws Exception {
        logger.info("SmsServiceImpl.singleSend params >> mobile:{}, text:{}", new Object[]{mobile, text});
        String domain = ConfigUtil.getConfig("SMS_DOMAIN");
        String uid = ConfigUtil.getConfig("SMS_UID");
        String pw = ConfigUtil.getConfig("SMS_PW");
        String PostData = "uid="+uid+"&pw="+pw+"&mb="+mobile+"&ms="+java.net.URLEncoder.encode(text,"utf-8");
        String ret = SMS(PostData, "http://"+domain+"/send.do");

        Integer code = 0;
        String sid = "";
        if(StringUtils.isNotBlank(ret)){
            if (ret.contains(",")) {
                String[] retarr = ret.split(",");
                code = Integer.parseInt(retarr[0]);
                sid = retarr[1];
            }

        }


        SmsRecord smsRecord = new SmsRecord();
        smsRecord.setSid(sid);
        smsRecord.setMobile(mobile);
        smsRecord.setText(text);
        smsRecord.setCode(code);
//        smsRecord.setMsg();
//        smsRecord.setCount();
//        smsRecord.setFee();
        smsRecord.setUid(bid);
        smsRecord.setIp(ip);

        logger.info("SmsServiceImpl.singleSend result << {}", smsRecord);
        return smsRecord;
    }
//
//    @Override
//    public ResultDO<SendSingleSmsInfo> tplSingleSend(String mobile, Long tplId, String tplValue) {
//        logger.info("SmsServiceImpl.tplSingleSend params >> mobile:{}, tplId:{}, tplValue:{}", new Object[]{mobile, tplId, tplValue});
//        YunpianRestClient client = new YunpianRestClient(ConfigUtil.getConfig("API_KEY_YUNPIAN"));
//        SmsOperator smsOperator = client.getSmsOperator();
//        ResultDO<SendSingleSmsInfo> result = smsOperator.tplSingleSend(mobile, String.valueOf(tplId), tplValue);
//        logger.info("SmsServiceImpl.tplSingleSend result << {}", result);
//        return result;
//    }
}
